<template>
  <div class="cabinet-detail-container">
    <el-card>
      <div slot="header" class="clearfix">
        <span>柜子 {{ cabinetId }} 详情</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="$router.push(`/cabinets/${area}/${row}`)"
        >
          返回排列表
        </el-button>
      </div>

      <div v-if="cabinet">
        <p>区域：{{ area }}</p>
        <p>排：{{ row }}</p>
        <p>编号：{{ cabinet.number }}</p>
        <p>状态：{{ getStatusText(cabinet.status) }}</p>

        <template v-if="cabinet.status === 'in_use'">
          <p>使用者：{{ cabinet.username }}</p>
          <p>开始时间：{{ formatDate(cabinet.startTime) }}</p>
          <p>使用密码：{{ cabinet.password }}</p>
        </template>

        <el-divider></el-divider>

        <h3>操作</h3>
        <div class="cabinet-actions">
          <template v-if="cabinet.status === 'available'">
            <el-button type="primary" @click="handleUseCabinet">使用柜子</el-button>
          </template>
          <template v-else-if="cabinet.status === 'in_use'">
            <el-button 
              type="danger" 
              @click="handleReleaseCabinet"
              v-if="cabinet.userId === user.id || isAdmin"
            >释放柜子</el-button>
          </template>
        </div>

        <el-divider></el-divider>

        
      </div>
      <div v-else>
        <el-alert title="柜子未找到" type="warning" show-icon></el-alert>
      </div>
    </el-card>

    <!-- 释放柜子需要密码确认的对话框 -->
    <el-dialog
      title="释放柜子"
      :visible.sync="releaseDialogVisible"
      width="30%"
      @close="releasePassword = ''"
    >
      <el-form>
        <el-form-item label="取件密码">
          <el-input v-model="releasePassword" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="releaseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmReleaseCabinet">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapGetters } from "vuex";

export default {
  name: "CabinetDetail",
  data() {
    return {
      releaseDialogVisible: false,
      releasePassword: ''
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
      allCabinets: (state) => state.cabinets.cabinets
    }),
    ...mapGetters(["getCabinetById", "getCabinetRecords"]),
    area() {
      return this.$route.params.area;
    },
    row() {
      return this.$route.params.row;
    },
    cabinetId() {
      return this.$route.params.cabinetId;
    },
    cabinet() {
      return this.getCabinetById(this.cabinetId);
    },
    isAdmin() {
      return this.user && this.user.role === "admin";
    },
    cabinetRecords() {
      return this.getCabinetRecords.filter((record) => record.cabinetId === this.cabinetId);
    }
  },
  mounted() {
    console.log('CabinetDetail.vue mounted');
    console.log('Cabinet ID from route:', this.cabinetId);
    console.log('Cabinet data:', this.cabinet);
  },
  watch: {
    '$route.params.cabinetId': {
      immediate: true,
      handler(newCabinetId) {
        if (!newCabinetId || !this.getCabinetById(newCabinetId)) {
          this.$router.replace('/cabinets').catch(()=>{});
        }
      }
    }
  },
  methods: {
    getStatusText(status) {
      const statusMap = {
        available: "空闲",
        in_use: "使用中"
      };
      return statusMap[status] || status;
    },
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },
    handleUseCabinet() {
      this.$store.dispatch("useCabinet", {
        cabinetId: this.cabinetId,
        userId: this.user.id
      }).then(({ password }) => {
        this.$message.success(`使用成功！取件密码：${password}`);
      }).catch(error => {
        this.$message.error(error.message || "使用失败");
      });
    },
    handleReleaseCabinet() {
      this.releaseDialogVisible = true;
    },
    confirmReleaseCabinet() {
      this.$store.dispatch("releaseCabinet", { cabinetId: this.cabinetId, password: this.releasePassword })
        .then(() => {
          this.$message.success("释放成功");
          this.releaseDialogVisible = false;
        }).catch(error => {
          this.$message.error(error.message || "释放失败");
        });
    }
  }
};
</script>

<style scoped>
.cabinet-detail-container {
  padding: 20px;
}

.cabinet-actions .el-button {
  margin-right: 10px;
}
</style>
